import React, { useState } from 'react';
import { Form, Input, Button, Modal, Table } from 'antd';
import { DeleteOutlined } from '@ant-design/icons';
import { useUpdate } from 'ahooks';
import styles from './index.less';

const usersKey = 'UsersKey';



const getUsers = () => {
  const usersStr = localStorage.getItem(usersKey)
  return usersStr ? JSON.parse(usersStr) : []
}

interface Usage {
  last: number
  now: number
  total: number
}

export default () => {
  const [form] = Form.useForm();
  const [userMap, setUserMap] = useState(new Map<string, Usage>())
  const users = getUsers()
  const update = useUpdate();
  const deleteUser = (user: string) => {
    userMap.delete(user)
    setUserMap(userMap)
    users.splice(users.findIndex((item: string) => item === user), 1)
    localStorage.setItem(usersKey, JSON.stringify(users))
    update()

  }
  const dataSource = getUsers().map((user: string) => {
    if (userMap.get(user)) {
      return {
        user,
        ...userMap.get(user)
      }
    }
    return { user }
  })
  const columns = [
    {
      title: '姓名',
      dataIndex: 'user',
      key: 'user',
    },
    {
      title: '上期度数',
      dataIndex: 'last',
      key: 'last',
    },
    {
      title: '本次度数',
      dataIndex: 'now',
      key: 'now',
    },
    {
      title: '操作',
      render: (record: any) => {
        const { user } = record
        return (<Button
          danger
          icon={<DeleteOutlined />}
          onClick={() => deleteUser(user)}
        />)
      }
    },
  ];
  const handleAddUser = () => {
    let userName = ''
    Modal.info({
      title: '添加用户',
      content: (
        <div>
          <Input placeholder="用户名" onChange={(value) => { userName = value.target.value }}/>
        </div>
      ),
      onOk: () =>{
        const users = getUsers()
        users.push(userName)
        localStorage.setItem(usersKey, JSON.stringify(users))
        update()
      },
    });
  }
  return (
    <div>
      <h1 className={styles.title}>7-1501电费水费计算器</h1>
      <div className={styles.calc}>
        <Form
          style={{ width: '740px' }}
          layout={'inline'}
          form={form}
        >
          <Form.Item label="总电费">
            <Input placeholder="" />
          </Form.Item>
          <Form.Item label="总水费">
            <Input placeholder="" />
          </Form.Item>
          <Form.Item>
            <Button type="primary">计算</Button>
            &nbsp;
            <Button type="primary" onClick={handleAddUser}>添加用户</Button>
          </Form.Item>
        </Form>
      </div>
      <div className={styles.table}>
        <Table dataSource={dataSource} columns={columns} />;
      </div>

    </div>
  );
}
